import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import Layout from '@/layouts/BasicLayout.vue'

// 白名单路由
const whiteList = ['/login']

// 基础路由（不需要权限）
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      hidden: true,
      title: '登录'
    }
  },
  {
    path: '/redirect',
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: ':path(.*)',
        component: () => import('@/views/redirect/index.vue'),
        meta: { title: '重定向', hidden: true }
      }
    ]
  },
  {
    path: '/',
    redirect: '/login',
    meta: { hidden: true }
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    meta: { hidden: true }
  },
  {
    path: "/profile",
    component:Layout,
    meta: { hidden: true },
    children: [
      {
        path: "",
        name: "Profile",
        component: () => import("@/views/profile/index.vue"),
        meta: { title: "个人中心", hidden: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = getToken()

  if (token) {
    if (to.path === '/login') {
      next()
    } else {
      try {
        // 获取用户权限路由
        const permissionStore = usePermissionStore()
        if (permissionStore.routes.length === 0) {
          // 获取路由
          const accessRoutes = await permissionStore.generateRoutesFn()
          // 动态添加路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          // 重新进入当前路由
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (error) {
        console.error('路由加载失败:', error)
        next('/login')
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

// 路由后置守卫
router.afterEach((to) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'
})

export default router
